#!/usr/bin/env node

const inquirer = require('inquirer')
const path = require('path')
const fs = require('fs')
const ejs = require('ejs')  // 模板引擎

inquirer
    .prompt([
        {
            type: 'input',
            name: 'name',
            message: 'Project name is:',
            default: 'lori-cli'
        },
        {
            type: 'list',
            name: 'templateName',
            choices: function(value) {
                let tmpDir = path.join(__dirname, 'templates')
                let fileList = fs.readdirSync(tmpDir)
                fileList.splice(-1, 0, new inquirer.Separator())
                return fileList
            },
            message: function(value) {
                return `which template will you choose for ${value.name}:`
            },
            default: 'default'
        },
        {
            type: 'checkbox',
            name: 'layout',
            message: 'what components would you like to render your homepage:',
            choices: ['header', 'nav', 'content', 'sidebar', 'footer']
        },
        {
            type: 'list',
            name: 'themeColor',
            message: 'which color would you like to render background:',
            choices: ['red', 'blue', 'yellow', 'white', new inquirer.Separator(), 'I want another color'],
            filter: function(value) {
                return value === 'I want another color' ? '' : value
            }

        },
        {
            type: 'input',
            name: 'themeColorSelf',
            message: 'input your favorite color in RGB <for example f04732>:',
            when: function(value) {
                return !value.themeColor
            },
            filter: function(value) {
                return '#' + value
            },
            validate: function(value) {
                return /^#[0-9a-fA-F]{6}$/.test(value)
            }
        }
    ])
    .then( answers => {
        // console.log(answers)
        // 将结果渲染至目标文件
        let templateDir = path.join(__dirname, 'templates', answers.templateName)
        let targetDir = process.cwd()  // 执行目录

        answers.themeColor = answers.themeColor || answers.themeColorSelf || 'white';
        // console.log(templateDir)
        // 读取文件
        fs.readdir(templateDir, (err, files) => {
            if(err) throw err

            files.forEach(file => {
                console.log('file', file, path.join(templateDir, file))
                // 渲染模板
                ejs.renderFile(path.join(templateDir, file), answers, (err, res) => {
                    // console.log('renderFile', res)
                    if(err) throw err
                    // 写入目标文件
                    fs.writeFileSync(path.join(targetDir, file), res)
                })
            })
        })
    })

